package com.electron.server.controller;

import com.electron.server.dto.QZJAnalysisStrainDTO;
import com.electron.server.dto.QZJAnalysisStrain_realTimeDTO;
import com.electron.server.dto.QiZhongJiRealTimeDTO;
import com.electron.server.service.impl.QZJAnalysisImpl;
import com.electron.server.service.impl.QZJAnalysis_realTimeImpl;
import com.electron.server.utils.api.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/qzj/realTime")
public class QiZhongJiRealTimeController {

    @Autowired
    QZJAnalysisImpl service;
    @Autowired
    QZJAnalysis_realTimeImpl realT;


    @PostMapping
    public CommonResult sendData(@RequestBody QiZhongJiRealTimeDTO data){
        //解析数据
        String[] d2 = data.getD().split(",");   //解析d数据
        String[] a2 = data.getA().split("|");   //解析a数据
        int cn = Integer.parseInt(d2[0]);
        String value = d2[1];

        // 存储数据到解析表
        QZJAnalysisStrainDTO dto = new QZJAnalysisStrainDTO();
        dto.setDeviceId(data.getA());
        dto.setUsername(a2[0]);
        dto.setPwd(a2.length >= 2 ? a2[1] : null);
        dto.setChannelNumber(cn);
        dto.setValue(value);
        dto.setTime(data.getE() == null ? data.getT():data.getE());
        dto.setPrj(data.getU());
        dto.setCc(data.getW());
        service.addQzjRealTime(dto);

        //分离实时表
        QZJAnalysisStrain_realTimeDTO real_dto_old = realT.getQzjRealTimeByDeviceIdAndChannelNumber(dto.getDeviceId(), dto.getChannelNumber());
        QZJAnalysisStrain_realTimeDTO real_dto_new = new QZJAnalysisStrain_realTimeDTO();

        real_dto_new.setDeviceId(dto.getDeviceId());
        real_dto_new.setCc(dto.getCc());
        real_dto_new.setChannelNumber(dto.getChannelNumber());
        real_dto_new.setPrj(dto.getPrj());
        real_dto_new.setPwd(dto.getPwd());
        real_dto_new.setTime(dto.getTime());
        real_dto_new.setUsername(dto.getUsername());
        real_dto_new.setValue(dto.getValue());
        //如果设备和通道号没有，则插入新数据
        if (real_dto_old == null){
            realT.addQzjRealTime(real_dto_new);
        }
        else {  //如果有，则更新
            realT.updateQzjRealTimeByDeviceId(real_dto_new);
        }
//        realT.addQzjRealTime(real_dto_new);

        return CommonResult.success(data);
    }

    @GetMapping
    public CommonResult testCon(){
        return CommonResult.success("success");
    }
}
